<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>vue3-指令轮播</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="/VUE/swiper/swiper-bundle.min.css">
    <script src="/VUE/swiper/swiper-bundle.min.js"></script>
    <script src="/VUE/vue3.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        .swiper {
            width: 1400px;
            height: 355px;
            margin: 20px auto;
            box-sizing: border-box;
            overflow: hidden;
        }

        .swiper img {
            width: 100%;
            height: 100%;
        }
    </style>
</head>

<body>
<header>导航栏</header>

<div class="swiper" id="box">
    <div class="swiper-wrapper">
        <div v-for="(item,index) in datalist" class="swiper-slide" :key="item"
             v-swiper="{index:index,length:datalist.length}">
            <img :src="item" alt="">
        </div>
    </div>
    <!-- 如果需要分页器 -->
    <div class="swiper-pagination"></div>
</div>

<footer>底部内容</footer>
</body>
<script>
    let obj = {
        data() {
            return {
                datalist: [],
            }
        },

        mounted() {
            setTimeout(() => {
                this.datalist = ["/images/01.jpg", "/images/02.jpg", "/images/03.jpg"]
            }, 2000)
        },
    }
    let app = Vue.createApp(obj)

    // vue3中指令生命周期，和组件生命周期相同，只差一个beforeCreate
    app.directive("swiper", {
        mounted(el, binding) {
            let {index, length} = binding.value;
            if (index === length - 1) {
                console.log({index, length})
                new Swiper(".swiper", {

                    loop: true, // 循环模式选项

                    // 如果需要分页器
                    pagination: {
                        el: '.swiper-pagination',
                    },

                    //自动轮播
                    autoplay: {
                        delay: 2500,
                        disableOnInteraction: false,
                    },
                })
            }
        },
    })

    app.mount("#box")

    /*
        2. 如果当前页面  状态不止datalist一个，其他状态更新， updated重新运行， new MySwiper 执行多次，会出现bug
     */

</script>
</html>